<!--
 * @Description: 基建出库退库----源单
 * @Version: 2.0
 * @Autor: gaofang
 * @Date: 2020-04-11 18:29:13
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-03-02 16:52:44
-->
<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据源单生成
    </a-button>

    <a-modal
      title="基建出库退库申请单生成退库单"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <!-- 公共部分 -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="申请日期">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select
                v-model="searchForm.documentClosed"
                style="width: 100%"
                @change="setDocumentClosed"
              >
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据号">
              <a-select
                v-model="searchForm.document"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="(item, index) in OrderList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item></a-col
          >
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="申请部门">
              <a-tree-select
                v-model="searchForm.deptId_dictText"
                show-search
                style="width: 100%"
                :tree-data="depTree"
                allow-clear
                @change="changeTreeNode"
              ></a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="库存组织">
              <a-select
                v-model="searchForm.pkCalbody_dictText"
                @change="getpk_calbodyId"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in InventoryOrganizationList"
                  :key="item.id"
                  :value="item.pkCalbody + '|' + item.bodyname"
                >
                  {{ item.bodyname }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="公司">
              <a-tree-select
                v-model="searchForm.pkCorp_dictText"
                show-search
                style="width: 100%"
                allow-clear
                :tree-data="pk_corpList"
                @change="getpk_corpId"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col> -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="在建项目">
            <a-select
              v-model="searchForm.cprojectid_dictText"
              @change="zaijianMethod"
              style="width: 100%"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in zaijianList"
                :key="index"
                :value="
                  item.jobcode + '|' + item.jobname + '|' + item.pkJobbasfil
                "
              >
                {{ item.jobname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          </a-col>

          <!-- 按钮 -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>

          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <a-col
            :xl="8"
            :lg="8"
            :md="8"
            :sm="24"
            :xs="24"
            :style="{ textAlign: 'right' }"
            ><div style="margin-top: 10px">
              <a-button type="primary" @click="Search()">查询</a-button>
              <a-button style="margin-left: 8px" @click="Reset()"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
        <a-row> </a-row>
      </a-form>

      <a-divider />

      <!-- 获取的基建出库单据表头部分 -->
      <a-table
        style="margin-top: 20px"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <template slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="updateDocumentClosed(record)"
          >
            <a>开启</a>
          </a-popconfirm>
          <a-popconfirm
            v-if="record.documentClosed == '关闭'"
            title="是否开启单据?"
            @confirm="updateDocumentClosed(record)"
          >
            <a>关闭</a>
          </a-popconfirm>
        </template>
      </a-table>

      <a-divider />
      <!-- 获取的基建出库单据中的物品 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="listDataSource"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <template slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="updateRecordClosed(record)"
          >
            <a>开启</a>
          </a-popconfirm>
          <a-popconfirm
            v-if="record.documentClosed == '关闭'"
            title="是否开启单据?"
            @confirm="updateRecordClosed(record)"
          >
            <a>关闭</a>
          </a-popconfirm>
        </template>
      </a-table>

      <!-- 备货通知单物品信息 -->
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import { infrasConsOutCancel } from "@/services/modules/tuiKuGuanLi/infrasConsOutCancel.js";
const $http = new infrasConsOutCancel();
import { JiJianChuKuHttp } from "@/services/modules/ChuKuGuanLi/JJianChuKu/JiJianChuKu";
const JiJianChuKu = new JiJianChuKuHttp(); // 基建出库



const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  {
    title: "订单单号",
    dataIndex: "document",
    key: "document",
    align: "center",
  },
  {
    title: "订单日期",
    dataIndex: "documentDate",
    key: "documentDate",
    align: "center",
  },

  {
    title: "申请部门",
    dataIndex: "deptId_dictText",
    key: "deptId_dictText",
    align: "center",
  },

  {
    title: "库存组织",
    dataIndex: "pkCalbody_dictText",
    key: "pkCalbody_dictText",
    align: "center",
  },
  // {
  //   title: "业务流程",
  //   dataIndex: "cbiztype_dictText",
  //   key: "cbiztype_dictText",
  //   align: "center",
  // },
  {
    title: "公司",
    dataIndex: "pkCorp_dictText",
    key: "pkCorp_dictText",
    align: "center",
  },
  {
    title: "在建项目",
    dataIndex: "cprojectid_dictText",
    key: "cprojectid_dictText",
    align: "center",
  },

  {
    title: "单据状态",
    dataIndex: "documentClosed",
    key: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

const listColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  // {
  //   title: "仓库编码",
  //   key: "depotNo",
  //   dataIndex: "depotNo",
  //   align: "center",
  // },
  // {
  //   title: "仓库名称",
  //   key: "depotId_dictText",
  //   dataIndex: "depotId_dictText",
  //   align: "center",
  // },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
    width: "200px",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit_dictText",
    dataIndex: "auxiliaryUnit_dictText",
    align: "center",
  },

  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
  },
  {
    title: "单价",
    dataIndex: "quanunitPricetity",
    key: "unitPrice",
    align: "center",
  },
  {
    title: "金额",
    dataIndex: "money",
    key: "money",
    align: "center",
  },

  {
    title: "单据状态",
    dataIndex: "documentClosed",
    key: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

export default {
  data() {
    return {
      zaijianList: [], // 在建项目列表

      depTree: [], // 部门列表
      saveid: "",
      InventoryOrganizationList: [], // 库存组织列表
      pk_corpList: [], // 公司列表

      // listSelectedRowKeys: [], // 下方表格选中按钮
      documentClosedList: ["开启", "关闭"],
      visible: false,
      searchForm: {
        deptId: "",
        pkCalbody: "",
        cbizid: "",
        cprojectid: "",
        document: "", //单据号
        rangeDate: null, // 日期范围
        documentClosed: "开启", //单据状态
      },
      saleDepartmentList: [], // 销售部门
      ClientList: [], // 客户列表
      OrderList: [], // 单据号列表

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      columns,
      dataSource: [],
      orderSelectedRowKeys: [],

      listColumns,
      listDataSource: [],
      listSelectedRowKeys: [], // 列表选择

      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },

      Form: {
        requisitionNo: "", // 订单号
        applicationDept: "", // 销售部门
        applicationDeptId: "", // 销售部门Id
        clientId: "", // 客户
        client: "", // 客户名称
        documentClosed: "", //单据状态
        goodsList: [], // 物品列表
      },
    };
  },
  mounted() {
    this.getSaleDepartmentList();
    this.getOrderList(); // 获取订单列表
    this.getDeparmentTree(); //获取部门树
    this.getSyncInventoryOrganizationList(); //获取库存组织
    this.getpk_corpList(); //公司
    this.getZaiJianList(); //在建项目列表

  },
  methods: {
    setDocumentClosed(value) {
      console.log("value", value);
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed === "关闭",
        },
      };
    },

    // 部门下拉框选择
    changeTreeNode(a) {
      console.log("a", a);
      let array = a.split("|");

      this.searchForm.deptId = array[0];
      this.searchForm.applicationDept = array[1];
      this.searchForm.deptId_dictText = array[1];
    },

    // 获取部门列表
    getDeparmentTree() {
      console.log("获取部门列表hanshu===");
      comHttp.getDepartmentList().then((res) => {
        if (res.success) {
          console.log("获取部门树", res);
          this.depTree = res.result;
          console.log(this.depTree, "111111111111111111");
          this.changeDeparmentData(this.depTree);
        }
      });
    },
    // 部门改变用友传递过来的数据为组件能识别的数据
    changeDeparmentData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeDeparmentData(element.children);
        }
        // element["title"] = element.deptname;
        // element["children"] = element.syncDepartmentFilesEntityList;
        // element["key"] = element.pkDeptdoc;
        // element["value"] = element.pkDeptdoc;

        // if (element.children) {
        //   this.changeCorpData(element.children);
        // }
      });
    },

    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value) {
      console.log("value", value);
      let array = value.split("|");
      this.searchForm.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.searchForm.pkCalbody);
    },

    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.pkCorp + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 获取公司Id
    getpk_corpId(value, label, extra) {
      console.log("11111111111111", value);
      console.log("2222222222", label);
      console.log("33333333333", extra);
      let array = value.split("|");
      this.searchForm.pkCorp = array[0];
      this.searchForm.pkCorpName = array[1];
    },

      //获取在建项目列表
    getZaiJianList() {
      JiJianChuKu.getZaiJian().then((res) => {
        console.log("在建项目", res);
        this.zaijianList = res.result;
      });
    },
    //在建项目触发函数
    zaijianMethod(value) {
      console.log("在建项目触发函数value", value);
      let array = value.split("|");
      this.searchForm.projectsUnderConstruction = array[2];
      this.searchForm.cprojectid = array[2];
      this.searchForm.cprojectid_dictText = array[1];
      console.log("在建项目触发函数this.Form", this.searchForm);
    },
    // 更新上方表格单据的状态函数
    updateDocumentClosed(record) {
      console.log("单据状态", record);
      if (record.documentClosed == "开启") {
        let data = {
          documentClosed: "关闭",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateStateUp(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据关闭成功！");
            this.getArrayListByOriginDocument(); //获取生产领料单内容
          } else {
            this.$message.error("单据关闭失败！");
          }
        });
      } else {
        let data = {
          documentClosed: "开启",
          id: record.id,
        };
        console.log("data====》", data);

        $http.updateStateUp(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据开启成功！");
            this.getArrayListByOriginDocument(); //获取生产领料单内容
          } else {
            this.$message.error("单据开启失败！");
          }
        });
      }
    },
    //关闭表格中的记录updateRecordClosed
    updateRecordClosed(record) {
      console.log("单据状态", record);
      if (record.documentClosed == "开启") {
        let data = {
          documentClosed: "关闭",
          id: record.objectInformationId,
        };
        console.log("data====》", data);

        $http.updateStateUn(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据关闭成功！");
            this.getArrayListByOriginDocumentHeaderId(this.saveid); //获取基建出库单内容
          } else {
            this.$message.error("单据关闭失败！");
          }
        });
      } else {
        let data = {
          documentClosed: "开启",
          id: record.objectInformationId,
        };
        console.log("data====》", data);

        $http.updateStateUn(data).then((res) => {
          if (res.code == 200) {
            this.$message.success("单据开启成功！");
            this.getArrayListByOriginDocumentHeaderId(this.saveid); //获取基建出库单内容
          } else {
            this.$message.error("单据开启失败！");
          }
        });
      }
    },
    // 列表选择事件
    listOnSelectChange(selectedRowKeys, selectedRows) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      console.log("selectedRows changed: ", selectedRows); //选中的数据
      this.listSelectedRowKeys = selectedRowKeys;
      this.originData = [];
      for (let i = 0; i < selectedRows.length; i++) {
        this.originData.push(selectedRows[i]);
      }
    },
    // ----------- 查询的单据为：退库申请已审核的、销售出库、已经审核的单据 --------------
    getArrayListByOriginDocument(
      queryPath = "?pageNo=1&pageSize=5&inOutIdentification=2&inOutCategoryIdentification=10&&auditMark=1&documentClosed=开启"
    ) {
      comHttp.getArrayListByApplyOriginDocument(queryPath).then((res) => {
        console.log("基建出库退库申请单:::::", res);
        this.dataSource = [];
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;
        this.dataSource = res.result.records;
        for (let i = 0; i < res.result.records.length; i++) {
          this.dataSource[i].key = (res.result.current - 1) * 5 + i + 1;
          this.dataSource[i].documentClosed =
            res.result.records[i].documentClosed == "关闭" ? "关闭" : "开启";
        }
      });
    },

    // 部门按钮触发
    DepartmentChange(value, options) {
      this.searchForm.deptId = options.key;
    },

    // 时间段
    getRangeTime(date, dateString) {
      this.searchForm.startTime = dateString[0];
      this.searchForm.endTime = dateString[1];
    },

    // 列表选择
    listSelectChange(selectedRowKeys, selectedRows) {
      this.listSelectedRowKeys = selectedRowKeys;
      console.log(selectedRows);
      this.Form.goodsList = selectedRows;
    },

    // 表单选择
    orderSelectChange(selectedRowKeys, selectedRows) {
      this.orderSelectedRowKeys = selectedRowKeys;
      console.log(selectedRows);
      (this.saveid = selectedRows[0].id), //
        // 单选 拿到表单信息
        (this.Form = selectedRows[0]);
      this.Form[`goodsList`] = [];

      this.getArrayListByOriginDocumentHeaderId(selectedRows[0].id);
    },

    // 通过基建出库单号ID,查询物品信息
    getArrayListByOriginDocumentHeaderId(id) {
      comHttp
        .getArrayListByApplyOriginDocumentHeaderId(
          "?id=" + id + "&inOutCategoryIdentification=10"
        )
        .then((res) => {
          console.log("物品信息::::::", res);
          this.listDataSource = res.result.list;
          this.Form.goodsList = res.result.list;

          for (let i = 0; i < this.Form.goodsList.length; i++) {
            this.Form.goodsList[i].key = i + 1;
            this.Form.goodsList[i].documentClosed =
              res.result.list[i].documentClosed == "关闭" ? "关闭" : "开启";
          }
        });
    },
    // 获取单据号列表
    getOrderList() {
      let queryPath = "?string=JJCKTS-";
      comHttp.getOrderListTuiKu(queryPath).then((res) => {
        console.log("获取销售订单列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.OrderList.push(res.result[i]);
        }
      });
    },
    // ----------- 重置 ------------------
    // 对话框取消
    handleCancel() {
      this.Reset();
      this.visible = false;
    },
    // 重置
    Reset() {
      // 重置查询条件
      this.searchForm = {
        deptId: "",
        pkCalbody: "",
        cbizid: "",
        cprojectid: "",
        document: "", //单据号
        rangeDate: null, // 日期范围
        documentClosed: "开启",
        startTime: "", // 开始日期
        endTime: "", // 结束日期
      };

      this.resetPagination(); // 重置分页情况
      this.getArrayListByOriginDocument(); // 重置基建出库单据、
      this.listDataSource = []; // 重置物品数据
      // 重置选择框中选中的值
      this.listSelectedRowKeys = [];
      this.orderSelectedRowKeys = [];
    },

    // 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      };
    },

    // ----------- 查询 ------------------
    // 查询
    Search() {
      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
      console.log("查询条件为:::", queryPath);
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
    },

    // 获取全局查询条件
    getQueryPath() {
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=5" +
        "&inOutIdentification=2&inOutCategoryIdentification=10&auditMark=1" +
        "&document=" +
        this.searchForm.document + // 单据号
        "&beginDate=" +
        this.searchForm.startTime +
        "&endDate=" +
        this.searchForm.endTime +
        "&documentClosed=" +
        this.searchForm.documentClosed +
        "&deptId=" +
        this.searchForm.deptId +
        "&pkCalbody=" +
        this.searchForm.pkCalbody +
        "&cbizid=" +
        this.searchForm.cbizid +
        "&cprojectid=" +
        this.searchForm.cprojectid;
      return queryPath; // 返回的查询条件
    },

    // 打开对话框
    showModal() {
      this.getArrayListByOriginDocument();
      this.visible = true;
    },
    // 对话框提交
    handleOk() {
      console.log("this.Form", this.Form);
      this.$emit("select-data", this.Form);
      this.visible = false;
      this.resetPagination(); // 重置分页
    },

    // ----------- 获取销售部门列表 --------------
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },
  },
};
</script>

<style>
</style>

